package cn.com.codes.testCasePackageManage.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import cn.com.codes.common.SecurityContextHolderHelp;
import cn.com.codes.common.util.StringUtils;
import cn.com.codes.framework.app.services.BaseServiceImpl;
import cn.com.codes.framework.hibernate.HibernateGenericController;
import cn.com.codes.framework.security.VisitUser;
import cn.com.codes.framework.security.filter.SecurityContextHolder;
import cn.com.codes.iteration.service.IterationService;
import cn.com.codes.object.IterationTestcasepackageReal;
import cn.com.codes.object.TestCaseInfo;
import cn.com.codes.object.TestCasePackage;
import cn.com.codes.object.TestCase_CasePkg;
import cn.com.codes.object.TestcasepkgOperationHistory;
import cn.com.codes.object.UserTestCasePkg;
import cn.com.codes.overview.dto.DataVo;
import cn.com.codes.testCasePackageManage.dto.PkgCaseInfo;
import cn.com.codes.testCasePackageManage.dto.PkgTestCaseReal;
import cn.com.codes.testCasePackageManage.dto.TestCasePackageDto;
import cn.com.codes.testCasePackageManage.service.TestCasePackageService;

public class TestCasePackageServiceImpl extends BaseServiceImpl implements TestCasePackageService {
	
	private static Logger loger = Logger.getLogger(TestCasePackageServiceImpl.class);
	private TestCasePackageService testCasePackageService;
	
	private IterationService iterationService;

	public void saveTestCasePackage(TestCasePackageDto testCasePackageDto){
		HashSet<String> testCaseIdsSet = new HashSet<String>();
		List<TestCase_CasePkg> testCase_CasePkgs_new = new ArrayList<TestCase_CasePkg>();
        String testPkgId = new String();
		String taskId = SecurityContextHolderHelp.getCurrTaksId();
		List<TestCaseInfo>  caseList = null;
		List<TestcasepkgOperationHistory> testcasepkgHistoryLists = new ArrayList<TestcasepkgOperationHistory>();
		if(!StringUtils.isNullOrEmpty(testCasePackageDto.getOtherTestPkgIds())) {
			caseList = this.copyTestCaseFromOtherTestPkg1(testCasePackageDto);
			int notExeCount = (caseList!=null&&caseList.size()>0)?caseList.size():0;
			testCasePackageDto.getTestCasePackage().setNotExeCount(notExeCount);
			if(caseList!=null&&caseList.size()>=1) {
				for(int j=0;j<caseList.size(); j++) {
					testCaseIdsSet.add(caseList.get(j).getTestCaseId().toString());
					TestcasepkgOperationHistory testcasepkgHistory = new TestcasepkgOperationHistory();
					testcasepkgHistory.setTaskId(taskId);
					testcasepkgHistory.setTestCaseId(caseList.get(j).getTestCaseId());
					testcasepkgHistory.setOperationPersonId(SecurityContextHolderHelp.getUserId());
					testcasepkgHistory.setOperationPersonName(SecurityContextHolderHelp.getMyRealName());
					testcasepkgHistory.setOperationTime(new Date());
					testcasepkgHistory.setOperationType("1");  //删除：0   增加：1
					testcasepkgHistoryLists.add(testcasepkgHistory);
					
				}
				
			}
		}else if(testCasePackageDto.getOtherCaseModuleNum().size()>0){
			if(!testCasePackageDto.getOtherCaseModuleNum().get(0).equalsIgnoreCase("")){
				String[] modules= testCasePackageDto.getOtherCaseModuleNum().get(0).split(",");
				List<String> moduleNumList = new ArrayList<String>();
			        if(modules.length>0){
			          for(int i=0;i<modules.length;i++) {
			        	  moduleNumList.add(modules[i]);
			          }
			        }
				List<TestCaseInfo> testCaseInfos=this.findCaseIdByModuleIds(moduleNumList,taskId,testCasePackageDto.getTagName(),testCasePackageDto.getStatus());
				if(testCaseInfos.size()>0) {
					for(int j=0;j<testCaseInfos.size(); j++) {
						testCaseIdsSet.add(testCaseInfos.get(j).getTestCaseId().toString());
						TestcasepkgOperationHistory testcasepkgHistory = new TestcasepkgOperationHistory();
						testcasepkgHistory.setTaskId(taskId);
						testcasepkgHistory.setTestCaseId(testCaseInfos.get(j).getTestCaseId());
						testcasepkgHistory.setOperationPersonId(SecurityContextHolderHelp.getUserId());
						testcasepkgHistory.setOperationPersonName(SecurityContextHolderHelp.getMyRealName());
						testcasepkgHistory.setOperationTime(new Date());
						testcasepkgHistory.setOperationType("1");  //删除：0   增加：1
						testcasepkgHistoryLists.add(testcasepkgHistory);
					}
					testCasePackageDto.getTestCasePackage().setNotExeCount(testCaseIdsSet.size());
				}
			}

		}
        
		this.add(testCasePackageDto.getTestCasePackage());
		
		testPkgId = testCasePackageDto.getTestCasePackage().getPackageId();
		Iterator<String> iterator  = testCaseIdsSet.iterator();
		while(iterator.hasNext()) {
			TestCase_CasePkg testCase_CasePkg = new TestCase_CasePkg();
			testCase_CasePkg.setPackageId(testPkgId);
			testCase_CasePkg.setTestCaseId(iterator.next());
			
			testCase_CasePkgs_new.add(testCase_CasePkg);
		}
		for(TestcasepkgOperationHistory testcasepkgHistory:testcasepkgHistoryLists) {
			testcasepkgHistory.setPackageId(testPkgId);
		}
		this.batchSaveOrUpdate(testCase_CasePkgs_new);
		
		this.saveUserTestCasePkg(testCasePackageDto);
		
		this.saveIterationAndTestCasePkg(testCasePackageDto);
		if(!testcasepkgHistoryLists.isEmpty()) {
			this.batchSaveOrUpdate(testcasepkgHistoryLists);
		}
		
	}
	
	
	/**
	 * 保存迭代中测试包与用例的关联信息
	 * @param testCasePackageDto 
	 */
	private void saveIterationAndTestCasePkg(TestCasePackageDto testCasePackageDto) {
		
		if(!StringUtils.isNullOrEmpty(testCasePackageDto.getIterationId()) && !StringUtils.isNullOrEmpty(testCasePackageDto.getTestCasePackage().getPackageId())){
			List<IterationTestcasepackageReal> iterationTestcaseList = new ArrayList<IterationTestcasepackageReal>();
			IterationTestcasepackageReal iterationTestcase = new IterationTestcasepackageReal();
			iterationTestcase.setIterationId(testCasePackageDto.getIterationId());
			iterationTestcase.setPackageId(testCasePackageDto.getTestCasePackage().getPackageId());
			iterationTestcaseList.add(iterationTestcase);
			iterationService.batchSaveTestCasePackage(iterationTestcaseList);
		}
		
	}

	public void updateTestCasePackage(TestCasePackageDto testCasePackageDto){
		this.update(testCasePackageDto.getTestCasePackage());
		
		if(!StringUtils.isNullOrEmpty(testCasePackageDto.getTestCasePackage().getPackageId())){
			this.deleteUserTestCasePkg(testCasePackageDto.getTestCasePackage().getPackageId());
			
		}
	
		this.saveUserTestCasePkg(testCasePackageDto);
	}
	
	public void deleteTestCasePkgById(String packageId){
	   this.delete(TestCasePackage.class, packageId);
	   this.deleteUserTestCasePkg(packageId);
	   this.deleteTestCase_CasePkg(packageId);
	}

	public String[] getUserIdsByPackageId(TestCasePackageDto testCasePackageDto){
		String hql = "from UserTestCasePkg  where packageId=?";
		@SuppressWarnings("unchecked")
		List<UserTestCasePkg> userTestCasePkgs = this.findByHql(hql, testCasePackageDto.getTestCasePackage().getPackageId());
		if(userTestCasePkgs != null && userTestCasePkgs.size() > 0){
			String[] userIds = new String[userTestCasePkgs.size()];
			for(int i=0;i<userTestCasePkgs.size();i++){
				userIds[i] = userTestCasePkgs.get(i).getUserId();
			}
			return userIds;
		}else{
			return null;
		}
	}
	
	public String[] getTestCaseIdsByPackageId(TestCasePackageDto testCasePackageDto){
		String hql = "from TestCase_CasePkg  where packageId=?";
		@SuppressWarnings("unchecked")
		List<TestCase_CasePkg> testCase_CasePkg = this.findByHql(hql, testCasePackageDto.getTestCasePackage().getPackageId());
		if(testCase_CasePkg != null && testCase_CasePkg.size() > 0){
			String[] testCaseIds = new String[testCase_CasePkg.size()];
			for(int i=0;i<testCase_CasePkg.size();i++){
				testCaseIds[i] = testCase_CasePkg.get(i).getTestCaseId();
			}
			return testCaseIds;
		}else{
			return null;
		}
	}
	
	private void saveUserTestCasePkg(TestCasePackageDto testCasePackageDto) {
		List<UserTestCasePkg> userTestCasePkgs = new ArrayList<UserTestCasePkg>();

		if(null !=testCasePackageDto.getSelectedUserIds()){
			String[] selectedIdList = testCasePackageDto.getSelectedUserIds().split(",");
			for(String selId:selectedIdList){
				UserTestCasePkg userTestCasePkg = new UserTestCasePkg();
				userTestCasePkg.setPackageId(testCasePackageDto.getTestCasePackage().getPackageId());
				userTestCasePkg.setUserId(selId);
				userTestCasePkgs.add(userTestCasePkg);
			}
		this.batchSaveOrUpdate(userTestCasePkgs);
	  }
	}

	private void deleteUserTestCasePkg(String packageId) {
		this.executeUpdateByHql("delete from UserTestCasePkg where packageId =? ", new Object[]{packageId});
	}
	
	public void reWriteEexRatio(String testCasepkgId) {
		TestCasePackage testCasePackage = super.getHibernateGenericController().findUniqueBy(TestCasePackage.class, "packageId", testCasepkgId);
		List<TestCase_CasePkg> testcasepkgList = this.findByProperties(TestCase_CasePkg.class,new String[]{ "packageId"},new Object[]{testCasepkgId});
		if(!testcasepkgList.isEmpty()) {
			int notExeCount = 0;
			int exeCount = 0;
			for(TestCase_CasePkg tpgCase :testcasepkgList){
				if(tpgCase.getExecStatus() !=null && tpgCase.getExecStatus() != 1){
					exeCount++;
				}
			}
			notExeCount=testcasepkgList.size()-exeCount;
			testCasePackage.setExeCount(exeCount);
			testCasePackage.setNotExeCount(notExeCount);
			this.saveOrUpdate(testCasePackage);
		}
		
	}
	
	public void saveTestCase_CasePkg(TestCasePackageDto testCasePackageDto) {
		String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
		String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
		String taskId = SecurityContextHolderHelp.getCurrTaksId(); 
		List<TestCase_CasePkg> testCase_CasePkgs = new ArrayList<TestCase_CasePkg>();
		List<TestcasepkgOperationHistory> testcasepkgHistoryLists = new ArrayList<TestcasepkgOperationHistory>();
        //选中的testcaseId		
		String[] selectedCaseIdList = testCasePackageDto.getSelectedTestCaseIds().split(",");
		Integer notExeCount = 0;
		Integer exeCount = 0;
		TestCasePackage testCasePackage = new TestCasePackage();
		
		List<TestCasePackage> testcasepkgList=this.findByProperties(TestCasePackage.class, new String[]{ "id"},new Object[]{testCasePackageDto.getTestCasePackage().getPackageId()});
		
		if(testcasepkgList.size()>0){
			testCasePackage = testcasepkgList.get(0);
		}
		
		//查询原有的数据
		List<TestCase_CasePkg> initCaseIdList = this.findByProperties(TestCase_CasePkg.class,new String[]{ "packageId"},new Object[]{testCasePackageDto.getTestCasePackage().getPackageId()});
	
		
		 Boolean existFlag = false; //true:找到已存在用例   false:新增用例
		for(int i=0;i<selectedCaseIdList.length;i++){
			existFlag = false;
			for(int j=0;j<initCaseIdList.size();j++){
				if(selectedCaseIdList[i].equals(initCaseIdList.get(j).getTestCaseId())){
					//保存原来用例的执行状态用于计算已执行用例数
					if(initCaseIdList.get(j).getExecStatus() !=null && initCaseIdList.get(j).getExecStatus() != 1){
						exeCount++;
					}
					existFlag = true;
					
					//移除
					initCaseIdList.remove(initCaseIdList.get(j)); 
					break;
				}
			}
			
			//新增用例包关联用例
			if(!existFlag){
				TestCase_CasePkg testCase_CasePkgNew = new TestCase_CasePkg();
				testCase_CasePkgNew.setPackageId(testCasePackageDto.getTestCasePackage().getPackageId());
				testCase_CasePkgNew.setTestCaseId(selectedCaseIdList[i]);
				testCase_CasePkgs.add(testCase_CasePkgNew);
				
				TestcasepkgOperationHistory testcasepkgHistory = new TestcasepkgOperationHistory();
				testcasepkgHistory.setPackageId(testCasePackageDto.getTestCasePackage().getPackageId());
				testcasepkgHistory.setTaskId(taskId);
				testcasepkgHistory.setTestCaseId(Long.parseLong(selectedCaseIdList[i]));
				testcasepkgHistory.setOperationPersonId(userId);
				testcasepkgHistory.setOperationPersonName(userName);
				testcasepkgHistory.setOperationTime(new Date());
				testcasepkgHistory.setOperationType("1");  //删除：0   增加：1
				testcasepkgHistoryLists.add(testcasepkgHistory);
			}
		}
		
		if(initCaseIdList.size()>0){
			for(int n=0;n<initCaseIdList.size(); n++){
				TestcasepkgOperationHistory testcasepkgHistory = new TestcasepkgOperationHistory();
				testcasepkgHistory.setPackageId(testCasePackageDto.getTestCasePackage().getPackageId());
				testcasepkgHistory.setTaskId(taskId);
				testcasepkgHistory.setTestCaseId(Long.parseLong(initCaseIdList.get(n).getTestCaseId()));
				testcasepkgHistory.setOperationPersonId(userId);
				testcasepkgHistory.setOperationPersonName(userName);
				testcasepkgHistory.setOperationTime(new Date());
				testcasepkgHistory.setOperationType("0");  //删除：0   增加：1
				testcasepkgHistoryLists.add(testcasepkgHistory);
				this.executeUpdateByHql("delete from TestCase_CasePkg where packageId =? and testCaseId=?", new Object[]{testCasePackageDto.getTestCasePackage().getPackageId(),initCaseIdList.get(n).getTestCaseId()});
			}
		}
		this.batchSaveOrUpdate(testCase_CasePkgs);
		
		this.batchSaveOrUpdate(testcasepkgHistoryLists);
		
		notExeCount = selectedCaseIdList.length-exeCount;
		testCasePackage.setExeCount(exeCount);
		testCasePackage.setNotExeCount(notExeCount);
		this.saveOrUpdate(testCasePackage);
	}
	
	private void deleteTestCase_CasePkg(String packageId){
		this.executeUpdateByHql("delete from TestCase_CasePkg where packageId =? ", new Object[]{packageId});
	}
	
	public void delTestCase_CasePkgByPkgCaseId(String pkgCaseId,String selCaseId,String packageId){
		  
				String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
				String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
				String taskId = SecurityContextHolderHelp.getCurrTaksId(); 
				
				List<TestcasepkgOperationHistory> testcasepkgHistoryLists = new ArrayList<TestcasepkgOperationHistory>();
				
				TestcasepkgOperationHistory testcasepkgHistory = new TestcasepkgOperationHistory();
				testcasepkgHistory.setPackageId(packageId);
				testcasepkgHistory.setTaskId(taskId);
				testcasepkgHistory.setTestCaseId(Long.parseLong(selCaseId));
				testcasepkgHistory.setOperationPersonId(userId);
				testcasepkgHistory.setOperationPersonName(userName);
				testcasepkgHistory.setOperationTime(new Date());
				testcasepkgHistory.setOperationType("0");  //删除：0   增加：1
				testcasepkgHistoryLists.add(testcasepkgHistory);
				
			this.executeUpdateByHql("delete from TestCase_CasePkg where pkgCaseId =? ", new Object[]{pkgCaseId});
			this.batchSaveOrUpdate(testcasepkgHistoryLists);
			
			TestCasePackage testCasePackage = new TestCasePackage();
			List<TestCasePackage> testcasepkgList=this.findByProperties(TestCasePackage.class, new String[]{ "id"},new Object[]{packageId});
			if(testcasepkgList.size()>0){
				testCasePackage = testcasepkgList.get(0);
				Integer notExeCount = testCasePackage.getNotExeCount();
				if(notExeCount !=null){
					if(notExeCount !=0){
						notExeCount--;
						testCasePackage.setNotExeCount(notExeCount);
						this.update(testCasePackage);
					}
					
				}
			}
	}
	
	public  List<PkgTestCaseReal> getSelTestCasesByPkgId(TestCasePackageDto testCasePackageDto){
		StringBuilder hqlStr = new StringBuilder();
		hqlStr.append("SELECT new cn.com.codes.testCasePackageManage.dto.PkgTestCaseReal(tt.testCaseId, tc.packageId " + 
			 " ) FROM cn.com.codes.object.TestCase_CasePkg tc " + 
             ",cn.com.codes.object.TestCaseInfo tt where tc.testCaseId = tt.testCaseId ");
                      
	      if(null != testCasePackageDto.getTestCasePackage()){
			if(null != testCasePackageDto.getTestCasePackage().getPackageId()){
				hqlStr.append(" and tc.packageId = '" + testCasePackageDto.getTestCasePackage().getPackageId() + "'");
			}
		  }
	      
	      if(null != testCasePackageDto.getQueryParam()){
	    	  if(!testCasePackageDto.getQueryParam().equals("-1")){
	    		  if(testCasePackageDto.getQueryParam().equals("1")){
	    			  hqlStr.append(" and ( tc.execStatus = '" + testCasePackageDto.getQueryParam() + "'");
	    			  hqlStr.append(" or tc.execStatus is null )");
		    	  }else{
						hqlStr.append(" and tc.execStatus = '" + testCasePackageDto.getQueryParam() + "'");
		    	  }
	    	  }
		  }
	      
	     List<PkgTestCaseReal> lists = this.findByHql(hqlStr.toString(), null);
	     return lists;
	}
	
	public  List<PkgCaseInfo> getPaginationForSelTestCasesByPkgId(TestCasePackageDto testCasePackageDto){
		StringBuilder hqlStr = new StringBuilder();
		hqlStr.append("SELECT new cn.com.codes.testCasePackageManage.dto.PkgCaseInfo(tc.pkgCaseId,tc.packageId,  tt.taskId,   tt.moduleId, " + 
			 " tt.testCaseId,   tt.createrId,   tt.prefixCondition, tt.testCaseDes,   tt.isReleased,   tt.creatdate, " +
			 " tt.attachUrl,   tt.caseTypeId,   tt.priId,   tt.weight, tc.execStatus as testStatus, " +
			 " tt.moduleNum,  tc.executorId as auditId, tt.OperDataRichText, tt.expResult,otl.moduleName) FROM cn.com.codes.object.TestCase_CasePkg tc " + 
             ",cn.com.codes.object.TestCaseInfo tt,cn.com.codes.object.OutlineInfo otl where tc.testCaseId = tt.testCaseId and tt.moduleId = otl.moduleId ");
                      
	      if(null != testCasePackageDto.getTestCasePackage()){
			if(null != testCasePackageDto.getTestCasePackage().getPackageId()){
				hqlStr.append(" and tc.packageId = '" + testCasePackageDto.getTestCasePackage().getPackageId() + "'");
			}
		  }
	      
	      if(null != testCasePackageDto.getQueryParam()){
	    	  if(!testCasePackageDto.getQueryParam().equals("-1")){
	    		  if(testCasePackageDto.getQueryParam().equals("1")){
	    			  hqlStr.append(" and ( tc.execStatus = '" + testCasePackageDto.getQueryParam() + "'");
	    			  hqlStr.append(" or tc.execStatus is null )");
		    	  }else{
						hqlStr.append(" and tc.execStatus = '" + testCasePackageDto.getQueryParam() + "'");
		    	  }
	    	  }
		  }
	      if(!StringUtils.isNullOrEmpty(testCasePackageDto.getTagName())){
	    	  hqlStr.append(" and (tt.tags like '%" + testCasePackageDto.getTagName() + "%' or otl.moduleName like '%" + testCasePackageDto.getTagName() + "%')" );
	      }
	      hqlStr.append(" order by tt.testCaseId ");
	      
	      testCasePackageDto.setHql(hqlStr.toString());
		  List<PkgCaseInfo> lists = this.findByHqlWithValuesMap(testCasePackageDto);
	      return lists;
	}
	
	public boolean reNameChkInTask(String objName,final String nameVal,final String namePropName,String idPropName,final String idPropVal,final String taskId){
		
		StringBuffer hql = new StringBuffer();
		hql.append("select count(").append(idPropName==null?"*":idPropName).append(")");
		hql.append(" from ").append(objName);
		hql.append(" where ").append(namePropName).append("=? and taskId=?");
		if(idPropName!=null&&!"".equals(idPropName.trim())&&idPropVal!=null&&!"".equals(idPropVal.trim())){
			hql.append(" and  ").append(idPropName).append("!=?");
		}
		final String countHql= hql.toString();
		List countlist = (List)this.hibernateGenericController.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)throws HibernateException {
				Query queryObject = session.createQuery(countHql).setCacheable(true);
				queryObject.setParameter(0, nameVal);
				queryObject.setParameter(1, taskId);
					if(idPropVal!=null&&!"".equals(idPropVal.trim())) {
						queryObject.setParameter(2, idPropVal);
					}
				return queryObject.list();
			}
		}, true);
		int count = HibernateGenericController.toLong(countlist.get(0)).intValue();
		return count>0?true:false;
	}	
	
	public DataVo getBugStaticsByPkgId(TestCasePackageDto testCasePackageDto){
		DataVo dataVo = new DataVo();
		String sql = "SELECT * FROM ( ( SELECT count(*) AS allcount FROM t_testcase_casepkg WHERE packageId = ? ) AS aa, " +
			  "( SELECT count(*) AS waitAuditCount FROM t_testcase_casepkg WHERE execStatus =0 AND packageId =? ) bb, " + 
			  "( SELECT count(*) AS passCount FROM t_testcase_casepkg WHERE ( execStatus = 2 ) AND packageId = ? ) dd, " + 
			  "(SELECT count(*) AS failedCount FROM t_testcase_casepkg WHERE execStatus = 3 AND packageId = ? ) ee, " + 
			  "( SELECT count(*) AS invalidCount FROM t_testcase_casepkg WHERE execStatus = 4 AND packageId = ?  ) ff, " + 
			  "( SELECT count(*) AS blockCount FROM t_testcase_casepkg WHERE execStatus = 5 AND packageId = ? ) gg," + 
			  "( SELECT count(*) AS waitModifyCount FROM t_testcase_casepkg WHERE execStatus = 6 AND packageId = ? ) hh ) " ;
		String pkgId = testCasePackageDto.getTestCasePackage().getPackageId();
		List<Object[]> countlist = this.findBySql(sql,null,pkgId,pkgId,pkgId,pkgId,pkgId,pkgId,pkgId);
		
		dataVo.setAllCount(Integer.parseInt(countlist.get(0)[0].toString()));
		dataVo.setWaitAuditCount(Integer.parseInt(countlist.get(0)[1].toString()));
		dataVo.setPassCount(Integer.parseInt(countlist.get(0)[2].toString()));
		dataVo.setFailedCount(Integer.parseInt(countlist.get(0)[3].toString()));
		dataVo.setInvalidCount(Integer.parseInt(countlist.get(0)[4].toString()));
		dataVo.setBlockCount(Integer.parseInt(countlist.get(0)[5].toString()));
		dataVo.setWaitModifyCount(Integer.parseInt(countlist.get(0)[6].toString()));
		
		return dataVo;
	}
	

	
	//执行用例成功后  更新已执行用例数 未执行用例数
	public void updateTestCasePkgExeCount(String testCasepkgId){
		List<TestCasePackage> testcasepkgList=this.findByProperties(TestCasePackage.class, new String[]{ "id"},new Object[]{testCasepkgId});
		TestCasePackage testCasePackage = new TestCasePackage();
		Integer exeCount = 0 ;
		 
		
		if(testcasepkgList.size()>0){
			testCasePackage = testcasepkgList.get(0);
			
			if(testCasePackage.getExeCount() != null){
				exeCount = testCasePackage.getExeCount();	
			}
			exeCount++;
			
			Integer notExeCount =  testCasePackage.getNotExeCount();
			if(notExeCount != null){
				if(notExeCount!=0){
					notExeCount--;
				}
			}else{
				notExeCount = 0 ;
			}
			
		
			testCasePackage.setExeCount(exeCount);
			testCasePackage.setNotExeCount(notExeCount);
			this.update(testCasePackage);
	    }
		
		
	}
	
	private HashSet<String> copyTestCaseFromOtherTestPkg(TestCasePackageDto testCasePackageDto) {
		String[] testPkgList = testCasePackageDto.getOtherTestPkgIds().split(",");
	    String newPkgId = testCasePackageDto.getTestCasePackage().getPackageId(); 
		
		HashSet<String> testCaseIdsSet = new HashSet<String>();
		for(int i=0;i< testPkgList.length; i++) {
		    //通过测试包id查询中间表获取该测试包中的执行用例
			List<TestCase_CasePkg> testCase_CasePkgs = this.findByProperties(TestCase_CasePkg.class,new String[]{ "packageId"},new Object[]{testPkgList[i]});
			if(testCase_CasePkgs.size()>0) {
				for(int j=0;j<testCase_CasePkgs.size(); j++) {
					testCaseIdsSet.add(testCase_CasePkgs.get(j).getTestCaseId());
				}
			}
		}
		
		return testCaseIdsSet;
	}
	
	private  List<TestCaseInfo> copyTestCaseFromOtherTestPkg1(TestCasePackageDto testCasePackageDto) {
		//其它测试包id
		String[] testPkgList = testCasePackageDto.getOtherTestPkgIds().split(",");
		//新增测试包的id
	    String newPkgId = testCasePackageDto.getTestCasePackage().getPackageId(); 
		
		//去重----使用set集合暂存测试包的执行用例id
		List<TestCaseInfo> testCaseIdsSet = new ArrayList<TestCaseInfo>();
		String likeString = "";
		String statusString = "";
		String packageIdString = "( ";
		for(int y=0;y<testPkgList.length;y++){
			if(y != testPkgList.length - 1){
				packageIdString = packageIdString + "'" + testPkgList[y].trim() + "'" + " ,";
			}else{
				packageIdString = packageIdString + "'" + testPkgList[y].trim() + "'";
			}
		}
		String taskId = SecurityContextHolderHelp.getCurrTaksId();
		packageIdString = packageIdString + " )";
		StringBuffer bugBoardSql = new StringBuffer();
		bugBoardSql.append("SELECT DISTINCT tescs.testcaseid as test_case_id ,tescs.testcasedes as test_case_des FROM t_testcasebaseinfo tescs   JOIN t_testcase_casepkg tests  ON tests.testcaseId = tescs.TESTCASEID and tescs.taskId='"+taskId +"'  AND tests.packageId IN ")
				   .append(packageIdString);
		if(testCasePackageDto.getTagName() != null && !"".equals(testCasePackageDto.getTagName().trim())){
			for(int i=0;i<testCasePackageDto.getTagName().split(" ").length;i++){
				if(i != testCasePackageDto.getTagName().split(" ").length - 1){
					likeString = likeString + " tescs.TAGS like " + "'%" + testCasePackageDto.getTagName().split(" ")[i].trim() + "%'" +" or ";
				}else{
					likeString = likeString + " tescs.TAGS like " + "'%" + testCasePackageDto.getTagName().split(" ")[i].trim() + "%'" ;
				}
			}
			likeString = " (" + likeString + " )";
			bugBoardSql.append(" AND ").append(likeString);
		}
		
		if(testCasePackageDto.getStatus() != null && !"".equals(testCasePackageDto.getStatus().trim())){
			for(int i=0;i<testCasePackageDto.getStatus().split(",").length;i++){
				if(i != testCasePackageDto.getStatus().split(",").length - 1){
					statusString = statusString + " tests.execStatus = " + Integer.parseInt(testCasePackageDto.getStatus().split(",")[i].trim()) +" or ";
				}else{
					statusString = statusString + " tests.execStatus = " + Integer.parseInt(testCasePackageDto.getStatus().split(",")[i].trim());
				}
			}
			statusString = " (" + statusString + " )";
			bugBoardSql.append(" AND ").append(statusString);
		}
		
		List<TestCaseInfo> list = this.getJdbcTemplateWrapper().queryAllMatchListWithFreePra(bugBoardSql.toString(), TestCaseInfo.class);
		
		return list;
	}
	
	public List<TestCaseInfo> findCaseIdByModuleIds(List<String> moduleNumList,String taskId,String tagName,String status){
		StringBuffer hql = new StringBuffer();
		Map praValuesMap = new HashMap();
	
		hql.append("select new TestCaseInfo(testCaseId,testCaseDes)");
		hql.append(" from TestCaseInfo  where taskId= :taskId "); 
		praValuesMap.put("taskId", taskId);
		for(int i=0;i<moduleNumList.size();i++){
			if(i==0){
				hql.append(" and (");
			}else{
				hql.append(" or");
			}
			if(moduleNumList.get(i)!=null&&!"".equals(moduleNumList.get(i))){
				hql.append(" moduleNum like :moduleNum"+i);
				praValuesMap.put("moduleNum"+i, moduleNumList.get(i)+"%");
			}
		}
		if(moduleNumList.size()>0){
			hql.append(")");
		}
		if(tagName != null && !"".equals(tagName.trim())){
			hql.append(" and ( ");
			for(int i=0;i<tagName.split(" ").length;i++){
				if(i != tagName.split(" ").length - 1){
					hql.append(" tags like :tags").append(i).append(" or ");
					praValuesMap.put("tags"+i, "%"+tagName.split(" ")[i].trim()+"%");
				}else{
					hql.append(" tags like :tags").append(i);
					praValuesMap.put("tags"+i, "%"+tagName.split(" ")[i].trim()+"%");
				}
			}
			hql.append(" )");
		}
		if(status != null && !"".equals(status.trim())){
			hql.append(" and ( ");
			for(int i=0;i<status.split(",").length;i++){
				if(i != status.split(",").length - 1){
					hql.append(" testStatus = :testStatus").append(i).append(" or ");
					praValuesMap.put("testStatus"+i, Integer.parseInt(status.split(",")[i].trim()));
				}else{
					hql.append(" testStatus = :testStatus").append(i);
					praValuesMap.put("testStatus"+i, Integer.parseInt(status.split(",")[i].trim()));
				}
			}
			hql.append(" )");
		}
		List<TestCaseInfo> testCaseInfos= this.findByHqlWithValuesMap(hql.toString(), praValuesMap,false);
		return testCaseInfos;
    }
	

	public IterationService getIterationService() {
		return iterationService;
	}


	public void setIterationService(IterationService iterationService) {
		this.iterationService = iterationService;
	}
	
}